package com.supermap.user.service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.supermap.dubbo.DataDubboConcumerService;
import com.supermap.tool.*;
import com.supermap.util.SQLFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.supermap.system.config.UserSession;
import com.supermap.user.entity.UserEntity;

@Service
public class UserService {


    public static JSONArray rolrArray = new JSONArray();

    @Resource
    private DataDubboConcumerService dataDubboConcumerService;

    @Autowired
    UserSession userSession;
    @Autowired
    TableTool tableTool;

    /**
     * @param @param  request
     * @param @return 设定文件
     * @return JSONObject    返回类型
     * @throws
     * @Title: getUserBySession
     * @Description: 获取session 中的用户信息
     */
    public JSONObject getUserBySession(HttpServletRequest request) {
        JSONObject user = null;
        if (request == null) {
            return user;
        }
        HttpSession si = request.getSession();
        if (si == null) {
            return user;
        }
        String sessionId = si.getId();
        if (StringTool.isNotNull(sessionId)) {
            HttpSession ss = UserSession.sessionMap.get(sessionId);
            if (ss == null) {
                return user;
            }
            Object se = ss.getAttribute("user");
            if (se != null) {
                user = (JSONObject) JSON.toJSON(se);
            }
        }
        return user;
    }

    /**
     * @param @param  user
     * @param @param  request
     * @param @return 设定文件
     * @return int    返回类型
     * @throws
     * @Title: saveUser
     * @Description: 添加用户信息
     */
    public int saveUser(UserEntity user, HttpServletRequest request) {

        try {
            MysqlEntity st = new MysqlEntity();
            st.setTableName("t_user");
            StringBuilder sql = new StringBuilder();
            sql.append("INSERT INTO t_user (loginName,showName,username,password,mobile,areaCode)VALUES(");
            sql.append("'" + user.getLoginName() + "',");
            sql.append("'" + user.getLoginName() + "',");
            sql.append("'" + user.getUsername() + "',");
            sql.append("'" + StringTool.getMD5(user.getPassword()) + "',");
            sql.append("'" + user.getMobile() + "',");
            if (StringTool.isNotNull(user.getArea())) {
                sql.append("'" + user.getArea() + "')");
            } else if (StringTool.isNotNull(user.getCity())) {
                sql.append("'" + user.getCity() + "')");
            } else if (StringTool.isNotNull(user.getProvince())) {
                sql.append("'" + user.getProvince() + "')");
            }

            st.setSql(sql.toString());
            dataDubboConcumerService.getDataWithInsert(sql.toString());

            st.setSql("select * from t_user where loginName = '" + user.getLoginName() + "'");
            dataDubboConcumerService.getDataWithSelect("select * from t_user where loginName = '" + user.getLoginName() + "'");

            JSONObject responseData = dataDubboConcumerService.getDataWithSelect("select * from t_user where loginName = '" + user.getLoginName() + "'");

            JSONArray newUserList = responseData.getJSONArray("data");
            String useerId;
            if (newUserList == null || newUserList.size() == 0) {
                useerId = null;
            } else {
                useerId = newUserList.getJSONObject(0).getString("id");
            }

            if (useerId != null) {
                String insertSql = "INSERT INTO t_user_role (userid,roleid)values('" + useerId + "','" + user.getRole() + "')";
                st.setSql(insertSql);
                responseData = dataDubboConcumerService.getDataWithInsert(insertSql);
                int status = responseData.getInteger("code");
                if (status == 200) {
                    return 0;
                } else {//数据回滚
                    String deleteSql = "DELETE FROM t_user_role WHERE loginName = '" + user.getLoginName() + "'";
                    st.setSql(deleteSql);
                    dataDubboConcumerService.getDataWithDelete(deleteSql);
                }
            }
            return 0;
        } catch (Exception e) {
            return -1;
        }

    }

    /**
     * @param @param  userid
     * @param @return 设定文件
     * @return int    返回类型
     * @throws
     * @Title: delUser
     * @Description: 注销用户
     */
    public int delUser(String userid) {
        MysqlEntity st = new MysqlEntity();
        JSONObject cv = new JSONObject();
        JSONObject uv = new JSONObject();

        st.setTableName("t_user");
        cv.put("id", userid);
        st.setConditionValue(cv);
        uv.put("del_flg", "1");
        st.setUpdateValue(uv);

        String selectSql = SQLFactory.getFastUpdateSql(st);
        JSONObject obj = dataDubboConcumerService.getDataWithUpdate(selectSql);

        if (obj.getInteger("code") == 200) {
            return 0;
        }
        return -1;
    }

    /**
     * @param @param  loginName
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: getUserLoginName
     * @Description: 判断 登录名是否重复
     */
    public boolean getUserLoginName(String loginName) {
        MysqlEntity st = new MysqlEntity();
        st.setTableName("sys_menu");
        String selectSql = "select loginName from t_user where loginName = '" + loginName + "'";
        st.setSql(selectSql);
        JSONObject responseData = dataDubboConcumerService.getDataWithSelect(selectSql);
        if (responseData.getInteger("code") != 200) {
            return false;
        }
        JSONArray userList = responseData.getJSONArray("data");
        if (userList.size() > 0 && userList.get(0) != null) {
            return false;
        }
        return true;
    }

    /**
     * @param @return 设定文件
     * @return Object    返回类型
     * @throws
     * @Title: getTreeList
     * @Description: 获取用户列表
     */
    public TableVoo getUserList(TableVoo table, UserEntity user, String areaCode) {

        StringBuilder sql = new StringBuilder();
        StringBuilder con = new StringBuilder();
        StringBuilder ggzd = new StringBuilder();

        con.append("SELECT COUNT(1) count FROM (");
        con.append("SELECT u.id FROM t_user u ");

        sql.append("SELECT u.*,r.id as roleid,r.name as roleName,r.code as roleCode,a.areaname FROM t_user u ");

        ggzd.append("LEFT JOIN  t_user_role ur ON u.id = ur.userid ");
        ggzd.append("LEFT JOIN t_role r ON ur.roleid = r.id ");
        ggzd.append("LEFT JOIN t_area a ON u.areaCode = a.areacode ");
        ggzd.append("WHERE u.del_flg = 0 AND u.username != 'admin' ");
        if (StringTool.isNotNull(areaCode)) {
            if (!"0".equals(areaCode)) {
                ggzd.append("AND u.areaCode REGEXP '^" + areaCode + "' ");
            }
        }
        if (StringTool.isNotNull(user.getUsername())) {
            ggzd.append("AND u.username = '" + user.getUsername() + "' ");
        }
        if (StringTool.isNotNull(user.getLoginName())) {
            ggzd.append("AND u.loginName = '" + user.getLoginName() + "' ");
        }
        if (StringTool.isNotNull(user.getMobile())) {
            ggzd.append("AND u.mobile = '" + user.getMobile() + "' ");
        }
        if (StringTool.isNotNull(user.getState())) {
            ggzd.append("AND u.state = " + user.getState() + " ");
        }
        if (StringTool.isNotNull(user.getRoleName())) {
            ggzd.append("AND r.id = " + user.getRoleName() + " ");
        }
        if (StringTool.isNotNull(user.getArea())) {
            ggzd.append("AND u.areaCode REGEXP '^" + user.getArea() + "' ");
        } else if (StringTool.isNotNull(user.getCity())) {
            ggzd.append("AND u.areaCode REGEXP '^" + user.getCity() + "' ");
        } else if (StringTool.isNotNull(user.getProvince())) {
            ggzd.append("AND u.areaCode REGEXP '^" + user.getProvince() + "' ");
        }

        con.append(ggzd + ") a");

        sql.append(ggzd);
        sql.append("ORDER BY u.createtime DESC ");

        return tableTool.getTable(table, sql.toString(), con.toString(), "t_user");
    }

    /**
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: userAudit
     * @Description: 用户审核
     */
    public boolean userAudit(String userId, int state) {
        MysqlEntity st = new MysqlEntity();
        JSONObject cv = new JSONObject();
        st.setTableName("t_user");
        cv.put("id", userId);
        st.setConditionValue(cv);
        JSONObject uv = new JSONObject();
        uv.put("state", state);
        st.setUpdateValue(uv);
        String updateSql = SQLFactory.getFastUpdateSql(st);
        JSONObject responseData = dataDubboConcumerService.getDataWithUpdate(updateSql);
        if (responseData.getInteger("code") == 200) {
            return true;
        }
        return false;
    }

    /**
     * @param @return 设定文件
     * @return JSONArray    返回类型
     * @throws
     * @Title: getUserRole
     * @Description: 获取角色列表
     */
    public JSONArray getUserRole(boolean gx) {
        if (rolrArray == null || gx) {
            MysqlEntity st = new MysqlEntity();
            st.setTableName("sys_menu");
            String selectSql ="select * from t_role where del_flg = 0";
            st.setSql(selectSql);
            JSONObject responseData = dataDubboConcumerService.getDataWithSelect(selectSql);
            if (responseData.getInteger("code") == 200) {
                if (responseData.getJSONArray("data") != null) {
                    rolrArray = responseData.getJSONArray("data");
                }
            }
        }
        return rolrArray;
    }

    /**
     * @param @param  areacode
     * @param @return 设定文件
     * @return JSONArray    返回类型
     * @throws
     * @Title: getUserArea
     * @Description: 获取用户区域
     */
    public com.alibaba.fastjson.JSONArray getUserArea(String areacode) {
        com.alibaba.fastjson.JSONArray areaArray = new com.alibaba.fastjson.JSONArray();
        MysqlEntity st = new MysqlEntity();
        st.setTableName("t_area");
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM t_area ");
        if (!StringTool.isNotNull(areacode)) {
            sql.append("WHERE LENGTH(areacode)= 2");
        } else {
            sql.append("WHERE LENGTH(areacode)= " + (areacode.length() + 2));
            sql.append(" AND areacode REGEXP '^" + areacode + "'");
        }
        st.setSql(sql.toString());
        com.alibaba.fastjson.JSONObject responseData = dataDubboConcumerService.getDataWithSelect(sql.toString());
        com.alibaba.fastjson.JSONArray dataArray = responseData.getJSONArray("data");
        if (dataArray != null) {
            areaArray = dataArray;
        }
        return areaArray;
    }

    /**
     * @param @param  loginName
     * @param @param  password
     * @param @param  reques
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: log
     * @Description: 登录逻辑
     */
    public int log(String loginName, String password, HttpServletRequest reques) {
        if (loginName == null || password == null) {
            return -1;
        }
        String md5 = StringTool.getMD5(password);
        StringBuilder sql = new StringBuilder();
        sql.append("select * from t_user where loginName = '");
        sql.append(loginName + "' ");
        MysqlEntity st = new MysqlEntity();
        st.setTableName("sys_menu");
        st.setSql(sql.toString());
//        String acwUrl = ThirdPortUrlTool.getThridLoginUrl(loginName,password);
//        JSONObject data = JSONObject.parseObject(HttpRequest.get(acwUrl));
        com.alibaba.fastjson.JSONObject responseData = dataDubboConcumerService.getDataWithSelect(sql.toString());
        if (responseData != null) {
            if (responseData.getInteger("code") != 200 || responseData.get("data") == null) {
                return 1;
            }
            com.alibaba.fastjson.JSONObject userJson = responseData.getJSONArray("data").getJSONObject(0);
            String userpassword = userJson.getString("password");
            String state = userJson.getString("state");
            if (userpassword == null) {
                return 2;
            }
            if (state == null || !"0".equals(state)) {
                return 1;
            }

            if (userpassword != null && md5.equals(userpassword)) {
                //登录成功
                //查询是否已经登录
                reques.getSession().removeAttribute("user");
                reques.getSession().setAttribute("user", userJson);
                String sessionid = UserSession.userMap.get(loginName);
                if (sessionid != null && !sessionid.equals("")) { //已经登录
                    //注销在线用户,如果session id 相同，不销毁。
                    if (!sessionid.equals(reques.getSession().getId())) {
                        userSession.destroyed(loginName, reques);
                        userSession.created(loginName, reques);
                    }
                } else {
                    //未登录 添加登录信息
                    userSession.created(loginName, reques);
                }
                return 0;
            } else {
                return -2;
            }
        }
        return -1;

    }

}
